﻿<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Request extends CI_Controller {

    function __construct() {
        parent::__construct();

        $this->load->helper('form');
        $this->load->helper('url');
        $this->load->model('Jobs');
    }

    function timeBased($editId = 0, $orderId = 0) {
        // modify menus
        $menus = $this->config->item('l_left_menu');
        if ($orderId > 0) {
            $menus['New']['Time Based'] = 'request/time-based/' . $editId . '/' . $orderId;
            $menus['New']['Trip Based'] = 'request/trip-based/' . $editId . '/' . $orderId;

            $this->config->set_item('l_left_menu', $menus);
        }

        $this->load->helper('url');
        $this->load->library('Menu');
        $menu = new Menu;
        $user = & Users::getInstance();

        $data = $menu->gen();
        $data['user'] = $user;
        if ($orderId > 0) {
            $data['jobs'] = $this->Jobs->getOrderJobs($orderId);

            $ji = $this->Jobs->getOrderJob($orderId);
            if ($ji->draft != "1") {
                $data['sendText'] = 'Resubmit for quote';
            } else {
                $data['sendText'] = 'Request for quote';
            }
        } else {
            $data['jobs'] = $this->Jobs->getJobs($user->id, 4);

            $data['sendText'] = 'Request for quote';
        }
        $data['editId'] = $editId;
        $data['orderId'] = $orderId;

        $this->load->view('time-based', $data);

        // if admin - he's using the transform feature, therefore we have to delete the jobs
        if ($user->level > 0) {
            
        }
    }

    function tripBased($editId = 0, $orderId = 0) {
        // modify menus
        $menus = $this->config->item('l_left_menu');
        if ($orderId > 0) {
            $menus['New']['Time Based'] = 'request/time-based/' . $editId . '/' . $orderId;
            $menus['New']['Trip Based'] = 'request/trip-based/' . $editId . '/' . $orderId;

            $this->config->set_item('l_left_menu', $menus);
        }

        $this->load->helper('url');
        $this->load->library('Menu');
        $menu = new Menu;
        $user = & Users::getInstance();

        $data = $menu->gen();
        $data['user'] = $user;
        if ($orderId > 0) {
            $data['jobs'] = $this->Jobs->getOrderJobs($orderId);

            $ji = $this->Jobs->getOrderJob($orderId);
            if ($ji->draft != "1") {
                $data['sendText'] = 'Resubmit for quote';
            } else {
                $data['sendText'] = 'Request for quote';
            }
        } else {
            $data['jobs'] = $this->Jobs->getJobs($user->id, 4);

            $data['sendText'] = 'Request for quote';
        }
        $data['editId'] = $editId;
        $data['orderId'] = $orderId;

        $this->load->view('trip-based', $data);

        // if admin - he's using the transform feature, therefore we have to delete the jobs
        if ($user->level > 0) {
            
        }
    }

    function termBased($orderId = 0) {
        $this->load->helper('url');
        $this->load->library('Menu');
        $menu = new Menu;
        $user = & Users::getInstance();

        $data = $menu->gen();
        $data['user'] = $user;
        if ($orderId > 0) {
            $data['jobs'] = $this->Jobs->getOrderJobs($orderId);

            $ji = $this->Jobs->getOrderJob($orderId);
            $data['job'] = $this->Jobs->getOrderJob($orderId);
            if ($ji->draft != "1") {
                $data['sendText'] = 'Resubmit for quote';
            } else {
                $data['sendText'] = 'Request for quote';
            }
        } else {
            $data['jobs'] = $this->Jobs->getJobs($user->id, 4);

            $data['sendText'] = 'Request for quote';
        }
        $data['orderId'] = $orderId;

        $this->load->view('term-based', $data);
    }

    function upload($orderId = 0) {
        $this->load->helper('url');
        $this->load->library('Menu');
        $menu = new Menu;
        $user = & Users::getInstance();

        $data = $menu->gen();
        $data['user'] = $user;
        $data['jobs'] = $this->Jobs->getJobs($user->id, 3);
        if ($orderId > 0) {
            $data['jobs'] = $this->Jobs->getOrderJobs($orderId);

            $ji = $this->Jobs->getOrderJob($orderId);
            $data['jobInfo'] = $this->Jobs->getOrderJob($orderId);
            if ($ji->draft != "1") {
                $data['sendText'] = 'Resubmit for quote';
            } else {
                $data['sendText'] = 'Request for quote';
            }
        } else {
            $data['jobs'] = $this->Jobs->getJobs($user->id, 4);

            $data['sendText'] = 'Request for quote';
        }
        $data['orderId'] = $orderId;

        $this->load->view('upload-itinerary', $data);
    }

    function ajaxAdd() {
        $user = & Users::getInstance();
        $type = $this->input->post('type');
        $owner = $user->id;
        if ($user->level > 0 && $this->input->post('belongsto') > 0) {
            $jo = $this->Jobs->getOrderJob($this->input->post('belongsto'));
            $owner = $jo->owner_id;
        }
        $status = "ok";
        switch ($type) {
            case 'time':
                //redirect('/');
                $formatJob = true;
                $editId = ($this->input->post('edit_id')) ? $this->input->post('edit_id') : 0;

                $result = $this->Jobs->createTime($this->input->post('startdate'), $this->input->post('enddate'), $this->input->post('passangers'), $this->input->post('hours'), $this->input->post('locObject'), '', $owner, 0, $editId);

                $orderId = $this->input->post('belongsto');
                if ($orderId > 0) {
                    $updateData = array(
                        'belongs' => $orderId,
                    );

                    $this->db->where('id', $result);
                    $this->db->update('jobs', $updateData);
                }
                break;
            case 'trip':
                $formatJob = true;
                $editId = ($this->input->post('edit_id')) ? $this->input->post('edit_id') : 0;
                $return = $this->input->post('returnres');
                $return_time = $this->input->post('return_time');
                $result = $this->Jobs->createTrip($this->input->post('startdate'), $this->input->post('passangers'), $this->input->post('from'), $this->input->post('locObject'), $return, '', $owner, 0, $editId, $return_time);

                $orderId = $this->input->post('belongsto');
                if ($orderId > 0) {
                    $updateData = array(
                        'belongs' => $orderId,
						'end_date' =>$return_time,
                    );

                    $this->db->where('id', $result);
                    $this->db->update('jobs', $updateData);
                }
                break;
            case 'term':
                $formatJob = true;
                $result = $this->Jobs->createTerm($this->input->post('startdate'), '', $owner, 0);
                break;
            case 'upload':
                $formatJob = false;
                $upDir = FCPATH . "uploads/itinerary/" . $user->id;
                if (!is_dir($upDir)) {
                    mkdir($upDir, 0777, true);
                }

                $config['upload_path'] = $upDir;
                $config['allowed_types'] = 'gif|jpg|png|psd|doc|docx|pdf|xls|txt';
                $config['encrypt_name'] = TRUE;

                $this->load->library('upload', $config);

                if (!$this->upload->do_upload()) {
                    //$error = array('error' => $this->upload->display_errors());
                    $status = $this->upload->display_errors();

                    //$this->load->view('upload_form', $error);
                } else {
                    $info = $this->upload->data();

                    $ext = $info['file_ext'];
                    if ($ext == ".xls") {
                        $t = "xls";
                    } elseif ($ext == ".doc" || $ext == ".docx") {
                        $t = "doc";
                    } elseif ($ext == ".pdf") {
                        $t = "pdf";
                    } elseif ($ext == ".txt") {
                        $t = "txt";
                    } elseif ($ext == ".bmp" || $ext == ".jpg" || $ext == ".jpeg" || $ext == ".gif" || $ext == ".png") {
                        $t = "img";
                    } else {
                        $t = "other";
                    }

                    $result = $this->Jobs->createUpload($info['file_name'], $t, $info['file_size'] * 1024, $info['orig_name'], '', $owner, 0);

                    $orderId = $this->input->post('belongsto');
                    if ($orderId > 0) {
                        $updateData = array(
                            'belongs' => $orderId,
                        );

                        $this->db->where('id', $result);
                        $this->db->update('jobs', $updateData);
                    }

                    //$this->load->view('upload_success', $data);
                }
                break;
        }

        $errors = new stdClass;
        $errors->{"status"} = $status;
        if ($status == "ok")
            $errors->{"job"} = $this->Jobs->getJob($result, $formatJob);

        echo json_encode($errors);
    }

    function ajaxDelete() {
        $user = & Users::getInstance();
        $job = $this->Jobs->getJob($this->input->post("id"));
        if (($user->id == $job->owner_id && $job->job_type == 3) || $user->level > 0) {
            $upDir = FCPATH . "/uploads/itinerary/" . $job->origid;
            unlink($upDir . "/" . $job->filename);
        }
        if ($user->level > 0) {
            $this->Jobs->delete($this->input->post("id"));
        } else {
            $this->Jobs->delete($this->input->post("id"), $user->id);
        }
    }

    function jobOrder() {
        $user = & Users::getInstance();
        $this->load->helper('url');
        $this->load->library('Menu');
        $this->load->library('email');

        // intial email
        $mailconf['mailtype'] = 'html';
        $this->email = new CI_Email($mailconf);

        $menu = new Menu;
        $user = & Users::getInstance();

        $data = $menu->gen();

        $sendMail = true;
        $orderId = $this->input->post('orderId');
        if ($this->input->post('type') == 'term') {
            if ($orderId > 0) {
                $upData = array("belongs" => $orderId);
                $this->db->delete('jobs', $upData);
            }

            $termId = $this->Jobs->createTerm($this->input->post('startdate'), '', $user->id, 0);

            if ($orderId > 0) {
                $updateData = array(
                    //'total_price' => 0,
                    'belongs' => $orderId,
                );

                $this->db->where('id', $termId);
                $this->db->update('jobs', $updateData);
            }
            $addType = "2";
        } elseif ($this->input->post('type') == 'upload') {
            $addType = "3";
        } else {
            $addType = "0";
        }
        if ($orderId > 0) {
            // draft based
            $jobOrderId = $orderId;

            if ($this->input->post('draft') != "1") {
                $updateData = array(
                    'draft' => 0,
                    'moreinfo' => $this->input->post('moreinfo')
                );

                $this->db->where('gid', $orderId);
                $this->db->update('job_group', $updateData);

                $this->Jobs->updatePrice($orderId, 0, 0, 0, 0, 0, '', 0);
                $this->Jobs->setMessage($orderId, 1, 1);
            }
        } else {
            $jobOrderId = $this->Jobs->jobOrder($user->id, $this->input->post('moreinfo'), $addType, $this->input->post('draft'));

            if ($user->level > 0) {
                $addUserId = $this->session->userdata('jobUserId');

                if ($addUserId > 0) {
                    // update jobs
                    $updateData = array(
                        'owner_id' => $addUserId,
                    );

                    $this->db->where('belongs', $jobOrderId);
                    $this->db->update('jobs', $updateData);

                    // update job group
                    $updateData = array(
                        'owner_id' => $addUserId,
                    );

                    $this->db->where('gid', $jobOrderId);
                    $this->db->update('job_group', $updateData);

                    $del = array('jobUserId' => '');
                    $this->session->unset_userdata($del);

                    $sendMail = false;
                }
            }
        }

        $data['jobOrderId'] = $jobOrderId;
        $data['user'] = $user;

        $isDraft = false;
        if ($this->input->post('draft') == "1") {
            $isDraft = true;
            $sendMail = false;
        }

        $this->Jobs->calcStartDate($jobOrderId);
        $this->Jobs->calcEndDate($jobOrderId);

        if ($user->id > 0) {
            if ($isDraft) {
                $message = '<p>You have successfully submitted the job order as draft. (Job ID ' . $this->Jobs->getID($jobOrderId) . ')</p>
					<p>To view, please go to ' . anchor('', 'dashboard') . '.</p>';

                $data['headerTitle'] = 'Success!';
            } else {

                if ($orderId < 1 && $user->level > 0 && $addUserId > 0) {
                    $message = '<p>You have successfully submitted the job order. (Job ID ' . $this->Jobs->getID($jobOrderId) . ')</p>
						<p>You can go back to your ' . anchor('', 'dashboard') . '.</p>';
                } else {
                    $message = '<p>You have successfully submitted the job order. (Job ID ' . $this->Jobs->getID($jobOrderId) . ')</p>
						<p>Please wait for a quotation from Book a bus administrator.</p>
						<p>You can go back to your ' . anchor('', 'dashboard') . '.</p>';
                }

                $data['headerTitle'] = 'Success!';

                if ($sendMail) {

                    $groupId = $jobOrderId;
                    $email = $user->username;
                    //$email = 'lptr@abv.bg';
                    $name = $user->name;

                    $ji = $this->Jobs->getOrderJobs($groupId);
                    $jobInfo = array();
                    foreach ($ji as $route) {

                        $jobInfo[] = nl2br($this->Jobs->formatJobInfoNoPrice($route));
                    }
                    $jobInfo[] = "\r\nMore info: " . nl2br($this->input->post('moreinfo'));

                    $this->email->from('ivy@bookabus.sg', 'Ivy');
                    $this->email->to($email);

                    $jsonFields = json_encode(array());
                    $inv = $this->Jobs->addInvoice($groupId, 0, $jsonFields, 1);

                    $this->email->subject('Bookabus.sg – Job Order #' . $this->Jobs->getID($groupId) . ' Submitted!');
                    $mmessage = 'Hello, ' . $name . ',
						<br /><br />
						You have successfully submitted the following job order for quotation:
						<br /><br />
						' . implode("<br/>", $jobInfo) . '
						<br /><br />
						<p>Thank you for enquiring, we will revert soon with a quotation for your confirmation and we will notify you via e-mail as soon as this happens.
						<br /><br />
                                                Should there be any changes to date, time, location, please login to your account and edit your job order accordingly and re-submit for a quote.
						<br/>
						A new quote will be presented to you.
						<br/><br/>
						Best Regards,
						<br />Ivy';
                    $this->email->message($mmessage);
                    $this->email->send();

                    // admin mail
                    $this->email->reply_to($email);
                    $this->email->from($email, $name);
                    $this->email->to('daniel_champion1101@yahoo.com');

                    //$this->email->subject('Bookabus.sg – Quote request on job #'.$this->Jobs->getID($groupId));
                    $this->email->subject('Bookabus.sg – Job #' . $this->Jobs->getID($groupId) . ' is edited');
                    $mmessage = implode("<br/>", $jobInfo) . '<br /><br />To reply or take action, click ' . anchor('/joborder/' . $groupId, 'here');
                    $this->email->message($mmessage);
                    $this->email->send();

                    /* ____send to developer______________________ */
                    $this->email->subject('Bookabus.sg - Job #' . $this->Jobs->getID($groupId) . ' is edited - request.php - line 440');
                    $this->email->to('hoang.dinh21@gmail.com');
                    $this->email->send();
                    /* __________________________________________ */
                }
            }
        } else {
            /* $message = '<p>You have successfully submitted the job order. (Job ID '.$jobOrderId.')</p>
              <p>Please enter your e-mail below for confirmation and further communication.</p>
              <p>We will generate a password and create your account automatically.</p>

              <div class="left-half">
              '.form_open('create-an-account', array('class' => 'standard-form')).'
              <input type="hidden" name="quickregister" value="1" />
              <div class="one">
              '.form_label('e-mail', 'email').'
              <div class="type-text">'.form_input(array('name' => 'email', 'id' => 'email')).'</div>
              <div class="clr"></div>
              </div>
              <div class="one">
              <div class="type-btn">'.form_submit('doregister', 'Submit').'</div>
              <div class="clr"></div>
              </div>
              </form>
              </div>'; */
            $draftString = "";
            if ($isDraft) {
                $draftString = '<input type="hidden" name="draft" value="1" />';
            }
            $message = '<p>You have successfully submitted the job order. (Job ID ' . $this->Jobs->getID($jobOrderId) . ')</p>
				<p>Please login below to continue.</p>
				<div>
					' . form_open('sign-in', array('class' => 'standard-form')) . '
						<input type="hidden" name="joblogin" value="1" />
                                                ' . $draftString . ' 
						<div class="one">
							' . form_label('e-mail', 'email') . '
							<div class="type-text">' . form_input(array('name' => 'email', 'id' => 'email')) . '</div>
							<div class="clr"></div>
						</div>
						<div class="one">
							' . form_label('Password', 'password') . '
							<div class="type-text">' . form_password(array('name' => 'password', 'id' => 'password')) . '</div>
							<div class="clr"></div>
						</div>
						<div class="one no-left">
							<div class="type-btn">' . form_submit('dologin', 'Submit') . '</div>
							<div class="clr"></div>
						</div>
					</form>
				</div>
				
				<p>Or enter your e-mail below for confirmation and further communication.</p>
				<p>We will generate a password and create your account automatically.</p>
				
				<div>
					' . form_open('create-an-account', array('class' => 'standard-form')) . '
						<input type="hidden" name="quickregister" value="1" />
						<div class="one">
							' . form_label('e-mail', 'email') . '
							<div class="type-text">' . form_input(array('name' => 'email', 'id' => 'email')) . '</div>
							<div class="clr"></div>
						</div>
						<div class="one no-left">
							<div class="type-btn">' . form_submit('doregister', 'Submit') . '</div>
							<div class="clr"></div>
						</div>
					</form>
				</div>';

            $data['headerTitle'] = 'Please proceed to login page';
        }
        $data['message'] = $message;

        $this->load->view('job-order', $data);
    }

    function jobAddandOrder_mobile() {
        //function jobOrder(){
        $this->load->helper('url');
        $this->load->library('Menu');
        $this->load->library('email');
        $mailconf['mailtype'] = 'html';
        //$this->email->initialize($mailconf);
        $this->email = new CI_Email($mailconf);
        $this->email->from('book@bookabus.sg');
        $this->email->to('hoang.dinh21@gmail.com');
        $this->email->subject('Mobile Bookabus.sg – Job Order Submitted!');

        $this->email->message('post type : ' . $this->input->post('type'));
        $this->email->send();

        $user = & Users::getInstance();
        $type = $this->input->post('type');
        $owner = $user->id;

        if ($user->level > 0 && $this->input->post('belongsto') > 0) {
            $jo = $this->Jobs->getOrderJob($this->input->post('belongsto'));
            $owner = $jo->owner_id;
        }
        $status = "ok";
        switch ($type) {
            case 'time':
                $formatJob = true;
                $editId = ($this->input->post('edit_id')) ? $this->input->post('edit_id') : 0;

                $result = $this->Jobs->createTime($this->input->post('startdate'), $this->input->post('enddate'), $this->input->post('passangers'), $this->input->post('hours'), $this->input->post('locObject'), '', $owner, 0, $editId);

                $orderId = $this->input->post('belongsto');
                if ($orderId > 0) {
                    $updateData = array(
                        'belongs' => $orderId,
                    );

                    $this->db->where('id', $result);
                    $this->db->update('jobs', $updateData);
                }
                break;
            case 'trip':
                $formatJob = true;
                $editId = ($this->input->post('edit_id')) ? $this->input->post('edit_id') : 0;
                $return = $this->input->post('returnres');
                $result = $this->Jobs->createTrip($this->input->post('startdate'), $this->input->post('passangers'), $this->input->post('from'), $this->input->post('locObject'), $return, '', $owner, 0, $editId);

                $orderId = $this->input->post('belongsto');
                if ($orderId > 0) {
                    $updateData = array(
                        'belongs' => $orderId,
                    );

                    $this->db->where('id', $result);
                    $this->db->update('jobs', $updateData);
                }

                break;
            case 'term':
                $formatJob = true;
                $result = $this->Jobs->createTerm($this->input->post('startdate'), '', $owner, 0);
                break;
            case 'upload':
                $formatJob = false;
                $upDir = FCPATH . "uploads/itinerary/" . $user->id;
                if (!is_dir($upDir)) {
                    mkdir($upDir, 0777, true);
                }

                $config['upload_path'] = $upDir;
                $config['allowed_types'] = 'gif|jpg|png|psd|doc|docx|pdf|xls|txt|csv';
                $config['encrypt_name'] = TRUE;

                $this->load->library('upload', $config);

                if (!$this->upload->do_upload()) {
                    //$error = array('error' => $this->upload->display_errors());
                    $status = $this->upload->display_errors();

                    //$this->load->view('upload_form', $error);
                } else {
                    $info = $this->upload->data();

                    $ext = $info['file_ext'];
                    if ($ext == ".xls") {
                        $t = "xls";
                    } elseif ($ext == ".doc" || $ext == ".docx") {
                        $t = "doc";
                    } elseif ($ext == ".pdf") {
                        $t = "pdf";
                    } elseif ($ext == ".txt") {
                        $t = "txt";
                    } elseif ($ext == ".bmp" || $ext == ".jpg" || $ext == ".jpeg" || $ext == ".gif" || $ext == ".png") {
                        $t = "img";
                    } else {
                        $t = "other";
                    }

                    $result = $this->Jobs->createUpload($info['file_name'], $t, $info['file_size'] * 1024, $info['orig_name'], '', $owner, 0);

                    //$this->load->view('upload_success', $data);
                }
                break;
        }

        $menu = new Menu;
        $user = & Users::getInstance();

        $data = $menu->gen();

        if ($this->input->post('doorder')) {
            if ($this->input->post('type') == 'term') {
                $addType = "2";
            } elseif ($this->input->post('type') == 'upload') {
                $addType = "3";
            } else {
                $addType = "4";
            }

            $message = '<p>Your have successfully submitted a request for quote.</p>
					<p>A quotation will be sent to your email account by our Bookabus administrator.</p>';

            $data['headerTitle'] = 'Submitted.';

            $email = $this->input->post('email');
            $name = $this->input->post('name');

            $ji = $this->Jobs->getJobs($user->id, $addType);
            $jobInfo = array();
            foreach ($ji as $route) {
                $jobInfo[] = nl2br($this->Jobs->formatJobInfo($route, true));

                if ($addType == "3") {
                    $updateData = array(
                        'sessionid' => '000000000000000',
                    );

                    $this->db->where('id', $route->id);
                    $this->db->update('jobs', $updateData);
                } else {
                    $deleteData = array('id' => $route->id);
                    $this->db->delete('jobs', $deleteData);
                }
            }
            if ($this->input->post('moreinfo'))
                $moreInfo = '<br/>More info: ' . nl2br($this->input->post('moreinfo'));
            else
                $moreInfo = '';

            if ($this->input->post('returntime'))
                $returnTime = '<br/>Return time: ' . nl2br($this->input->post('returntime'));
            else
                $returnTime = '';

            // user message
            $this->email->from('book@bookabus.sg');
            $this->email->to($email);

            $this->email->subject('Bookabus.sg – Job Order Submitted!');
            $mmessage = "Hello, " . $name . ",
					\n\n<br /><br /> 
					You have successfully submitted the following job order for quotation:
					\n\n<br /><br />
					" . implode("\n\n<br/><br/>", $jobInfo) . "
					" . $moreInfo . $returnTime . "
					\n\n<br /><br />
					Thank you for enquiring, we will revert soon with a quotation for your confirmation and we will notify you via e-mail as soon as this happens.
					\n\n<br /><br />
					<b>Best Regards,
					\n<br />Ivy</b>
					\n<br/><br/><img src=\"" . site_url() . "/assets/images/bookabus.png\" alt=\"Bookabus\" />
					\n<br/>BookaBus Pte Ltd
					\n<br/>Address: 20 Bukit Batok Crescent, #09-07 Enterprise Centre, Singapore 658080
					\n<br/><a href=\"http://www.bookabus.sg\">http://www.bookabus.sg</a>";
            $this->email->message($mmessage);
            //abort
            $this->email->send();

            // admin message
            $this->email->to('book@bookabus.sg');
            $this->email->reply_to($email);
            $this->email->from($email, $name);

            $this->email->subject('Bookabus.sg – Job Order Submitted!');
            $mmessage = $name . " has requested a quotation for the following job order:
					\n<br />
					" . implode("\n\n<br/><br/>", $jobInfo) . "
					" . $moreInfo . $returnTime . "
					\n\n<br /><br />
					Customer detail:
					\n<br />
					Name: " . $name . "
					\n<br/>Company name: " . $this->input->post('cname') . "
					\n<br/>Phone: " . $this->input->post('number') . "
					\n<br/>E-mail: " . $email;
            $this->email->message($mmessage);
            //abort
            $this->email->send();


            /* ___________to developer______________ */

            $this->email->from($email, $name);
            $this->email->to('hoang.dinh21@gmail.com');
            $this->email->subject('Bookabus.sg – Job Order Submitted! - Developer Test ling 907 request.php');
            $this->email->send();
            /* ___________end to developer______________ */
        } else {
            if ($this->input->post('type') == 'term') {
                $this->Jobs->createTerm($this->input->post('startdate'), '', $user->id, 0);
                $addType = "2";
            } elseif ($this->input->post('type') == 'upload') {
                $addType = "3";
            } else {
                $addType = "4";
            }

            $message = '
				<p>To complete your job order, please enter your personal information for further communication.</p>
				
				<div class="left-half">
					' . form_open('request/jobOrder', array('class' => 'standard-form')) . '
						<div class="one">
							' . form_label('Name *', 'name') . '
							<div class="type-text">' . form_input(array('name' => 'name', 'id' => 'name')) . '</div>
							<div class="clr"></div>
						</div>
						<div class="one">
							' . form_label('Company Name', 'cname') . '
							<div class="type-text">' . form_input(array('name' => 'cname', 'id' => 'cname')) . '</div>
							<div class="clr"></div>
						</div>
						<div class="one">
							' . form_label('Contact Number *', 'number') . '
							<div class="type-text">' . form_input(array('name' => 'number', 'id' => 'number')) . '</div>
							<div class="clr"></div>
						</div>
						<div class="one">
							' . form_label('E-mail *', 'email') . '
							<div class="type-text">' . form_input(array('name' => 'email', 'id' => 'email')) . '</div>
							<div class="clr"></div>
						</div>
						<div class="one">
							<div class="type-btn">' . form_submit('doorder', 'Submit') . '</div>
							<div class="clr"></div>
						</div>
						<input type="hidden" name="moreinfo" value="' . htmlspecialchars($this->input->post('moreinfo')) . '" />
						<input type="hidden" name="type" value="' . htmlspecialchars($this->input->post('type')) . '" />
					</form>
				</div>
				
				<script type="text/javascript">
					jQuery("input[name=name], input[name=number], input[name=email]").change(function() {
						if (jQuery(this).val() != "") {
							jQuery(this).parent().parent().children("label").css("color", "");
						}
					});
					
					jQuery("form.standard-form").submit(function() {
						if (jQuery("input[name=name]").val() == "" || jQuery("input[name=number]").val() == "" || !isPhone(jQuery("input[name=number]").val()) || jQuery("input[name=email]").val() == "") {
							alert("Please fill all the fields, marked with *");
							
							jQuery("input[name=name], input[name=number], input[name=email]").each(function() {
								if (jQuery(this).val() == "" || (jQuery(this).attr("name") == "number" && !isPhone(jQuery(this).val()))) {
									jQuery(this).parent().parent().children("label").css("color", "#ff0000");
								}
							});
							
							return false;
						} else {
							if (validateEmail(jQuery("input[name=email]").val())) {
								return true;
							} else {
								jQuery("input[name=email]").parent().parent().children("label").css("color", "#ff0000");
								alert("Invalid e-mail");
								
								return false;
							}
						}
					});
				</script>';

            $data['headerTitle'] = 'Enter information to continue';
        }

        $data['message'] = $message;

        $this->load->view('job-order', $data);
    }

    function delete($jid) {
        $user = & Users::getInstance();
        $this->load->helper('url');
        $this->load->library('Menu');
        $this->load->library('email');

        // intial email
        $mailconf['mailtype'] = 'html';
        $this->email = new CI_Email($mailconf);

        $menu = new Menu;
        $user = & Users::getInstance();

        $this->Jobs->deleteJobOrder($jid);

        redirect('/');
    }

    function reuse($jid) {
        $user = & Users::getInstance();
        $this->load->helper('url');
        $this->load->library('Menu');
        $this->load->library('email');
        $this->load->model('Chats');

        $data['job'] = $this->Jobs->getOrderJob($jid);
        $owner_id = $data['job']->owner_id;
        $menu = new Menu;
        $user = & Users::getInstance();
        $this->Chats->post($jid, $user->id, 'I have just reused the job order.', 0);
        $this->Jobs->updateJobGroup($jid);

        // intial email
        $mailconf['mailtype'] = 'html';
        $this->email = new CI_Email($mailconf);
        $menu = new Menu;
        $user = & Users::getInstance();
        $email = $user->username;
        $sname = $user->name;

        $data = $menu->gen();
        $data['user'] = $user;

        if (($data['job']->owner_id == $user->id) || ($user->id == 1)) {
            $uinfo = $user->getUserInfo($owner_id);
            $mail = $uinfo->email;
            $name = $uinfo->name;
            $this->email->message('Admin has create a job order ( #' . $jid . ' ) for you on your behalf.
				<br /><br />
				To take action, click ' . anchor('/joborder/' . $jid, 'here'));
            $this->email->from('ivy@bookabus.sg', 'Ivy');


            /* _____ mail to user____________________________ */
            $this->email->to($mail);
            $this->email->subject('Bookabus.sg – Reuse Job');
            $this->email->send();
            /* ____________________________________________ */



            /* ____send to developer______________________ */
            $this->email->subject('Bookabus.sg - Reuse Job');
            $this->email->to('hoang.dinh21@gmail.com');
            $this->email->send();
            /* __________________________________________ */
        }
        redirect('');
    }

    function userpaid($jid) {
        $this->load->helper('url');
        $this->load->library('Menu');
        $this->load->model('Chats');
        $menu = new Menu;
        $user = & Users::getInstance();
        $data = $menu->gen();

        if ($user->level > 0) {
            $j = $this->Jobs->getOrderJob($jid);
            $data['job'] = $j;

            if ($j->cancel == 1) { // cancellation payment
                $price = $j->cancelfee;
            } else { // normal payment
                $price = $this->Jobs->neededPayment($jid);
            }

            $text = '<p>The user has paid the amount of ' . $this->Jobs->formatPrice($price) . ' on ' . date("j M Y") . '.</p>';
            $paymentType = 5;
            $type = 5;
            $paid = $price;

            $this->Chats->post($jid, $user->id, $text, $type, $paid, $paymentType);

            if ($j->cancel == 1) {
                $this->Jobs->setCancelPaid($jid);

                $this->Jobs->changeStatus($jid, 8);

                $this->Chats->post($jid, 0, '<p>The job order is now cancelled.</p>', 7);
            } else {
                $this->Jobs->addPayment($jid, $price);

                // update job status
                if ($data['job']->status < 4) {
                    $this->Jobs->changeStatus($jid, 4);
                } else {
                    $this->Jobs->changeStatus($jid, 7);

                    $this->Chats->post($jid, 0, '<p>Job order is now successfully finished and closed.</p>', 7);
                }
            }

            $this->Jobs->setMessage($jid, 1, 0);

            redirect('/joborder/' . $jid);
        } else {
            redirect('/');
        }
    }

}

/* End of file request.php */
/* Location: ./application/controllers/request.php */